package cn.yj.wx.pay.service.handler;

import cn.yj.common.emums.PayFrom;
import cn.yj.wx.pay.config.PayConfig;
import cn.yj.wx.pay.enrity.AppPayOrderResult;
import cn.yj.wx.pay.enrity.WechatPayRequest;
import cn.yj.wx.pay.utils.WxPayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.UUID;

/**
 * @author 永健
 * @since 2021-09-22 16:32
 */
public class AppPay extends AbstractWxPay<AppPayOrderResult, WechatPayRequest> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppPay.class);

    private static final String PAY_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";

    @Resource
    private PayConfig payConfig;

    /**
     * 将结果进行sign签名
     *
     * @param payResult
     */
    @Override
    protected void requestPayAfter(AppPayOrderResult payResult) throws NoSuchAlgorithmException, SignatureException,
            InvalidKeyException {
        String prepayid = payResult.getResult();
        PayConfig config = super.config();

        String appid = config.getAppId();
        String partnerid = config.getMchId();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");

        StringBuffer toBeSignStr = new StringBuffer();
        toBeSignStr.append(appid).append("\n");
        toBeSignStr.append(timestamp).append("\n");
        toBeSignStr.append(nonceStr).append("\n");
        toBeSignStr.append(prepayid).append("\n");

        // 签名
        String v3Sign = WxPayUtils.v3Sign(toBeSignStr.toString(), getPrivateKey());

        AppPayOrderResult.Payment payment = new AppPayOrderResult.Payment();
        payment.setAppid(appid);
        payment.setPrepayid(prepayid);
        payment.setPartnerid(partnerid);
        payment.setNonceStr(nonceStr);
        payment.setTimeStamp(timestamp);
        payment.setPaySign(v3Sign);
        payResult.setPayment(payment);
        LOGGER.info(payment.toString());
    }

    @Override
    public AppPayOrderResult underOrder(WechatPayRequest wechatPayRequest) {
        AppPayOrderResult appPayOrderResult = super.doUnderOrder(PAY_URL, wechatPayRequest);
        appPayOrderResult.setOutTradeNo(wechatPayRequest.getOut_trade_no());
        appPayOrderResult.setTotalAmount(wechatPayRequest.getAmount().getTotal().toString());
        return appPayOrderResult;
    }

    @Override
    PayConfig config() {
        return payConfig;
    }

    @Override
    public boolean support(PayFrom payFrom) {
        return payFrom == PayFrom.APP;
    }

}
